Understanding the Modern Web Stack: Webpack 您所在的位置:网站首页 Concepts webpack Understanding the Modern Web Stack: Webpack

Understanding the Modern Web Stack: Webpack

2024-05-21 00:22| 来源: 网络整理| 查看: 265

(This tutorial is written using webpack v5 however the general concepts will apply to any version)

Table of Contents What is Webpack? Prerequisites Initializing the Project Why Bundling? Installing Webpack Webpack Plugins Modules in Javascript Modules in webpack Minimizing Bundle Size Wrapping Up What is webpack?

In webpack's own words:

At its core, webpack is a static module bundler for modern JavaScript applications. When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.

If you find it difficult to understand exactly what that means, don't worry at all, that's why we're here!

Many of us, including myself, first seek out webpack tutorials when we reach a point with our projects when we know we need it -- but we may not know exactly what we need it to do, or the specific terms to describe the problems we are trying to solve.

webpack (stylized with a lowercase w) is extremely configurable and customizable by design, which means that at the cost of a slightly higher learning curve than an out-of-the-box solution, you get incredible power to do whatever it is you need to do.

If webpack core doesn't do it, you can get a plugin. If you can't find a plugin for it, you can write your own plugin. You're probably getting the idea at this point.

The idea behind this tutorial is that we will keep things as simple as possible. Start with a super basic web app / page, and gradually add pieces as you would on a real project until you encounter a scenario where you realize webpack would help.

At that point we install, configure, and add it to our project.

So we're ready to dive in -- but before we do there are a few prerequisites we should address first.

Prerequisites

You will need to have Node.js installed on your machine and available from your terminal. Installing Node will automatically install npm as well, which is what you will use to install Babel.

Open up your terminal of choice. If you see version numbers when running the two commands below (your numbers will likely be different than this example) then you are ready to go:

node --version > v15.5.0 npm --version > 7.16.0 Enter fullscreen mode Exit fullscreen mode

You will want to have at least a basic understanding of Javascript. We don't deal with any complicated code in this tutorial, but we'll assume you can comfortable read simple programs. webpack's configuration file is written in JS format.

We will assume you have the ability to run a local server and test the HTML/JS code we are using. If not, then check out this tutorial first:

Understanding the Modern Web Stack: Running a Local Web Server Initializing the Project

Let's start by initializing a new npm project. Run the following command to generate one:

npm init -y Enter fullscreen mode Exit fullscreen mode

The -y flag will automatically select default values for everything, which is appropriate in our example.

We'll start by creating an HTML entry point where we can load and test our bundle. Any basic HTML template will work. Create a file called index.html in your root directory. If you are using VS Code you can generate an instant template by opening the file and typing ! (then click ! menu).

Otherwise we can use the template below:

index.html

Document Enter fullscreen mode Exit fullscreen mode

Next we will create a directory called src. in the root directory of your project. Inside that directory we will have a file called script.js with the following code:

src/script.js

function component() { const element = document.createElement('div'); // Lodash, currently included via a script, is required for this line to work element.innerHTML = _.join(['Hello', 'webpack'], ' '); return element; } document.body.appendChild(component()); Enter fullscreen mode Exit fullscreen mode

(You will notice that at this beginning stage we are essentially following along with webpack's own fantastic Getting Started guide. webpack's documentation is known for being extremely high quality thanks to its amazing contributors.)

You may notice that we are using a Lodash function inside our script.js file. That's the little _ underscore variable with the join() method. Might be a bit of a simplistic example, but you can replace it with any scenario you can imagine where you might want to use the benefit of an external library function rather than coding it yourself.

Since we are using Lodash in our file, we'll need to add it to our project. From the root directory run the following terminal command:

npm install lodash Enter fullscreen mode Exit fullscreen mode

Now your directory structure should look like this:

root │ index.html | package.json └───node_modules └───src │ │ script.js Enter fullscreen mode Exit fullscreen mode

Next we need to load both our script.js file and the Lodash library into out index.html to see everything work together. Update your index.html file like so:

index.html

Webpack Example Enter fullscreen mode Exit fullscreen mode

Make sure to notice a couple about our script tags. script.js must be prefixed with src/ as it is in that directory, and since our JS is working with the DOM, we want to use the defer attribute so that it doesn't load until after the HTML is finished parsing.

At this point you can serve up your root directory and you should be able to see the following result:

Page Example

If you are not sure how to host a local server check out this post to help get you up and running:

Understanding the Modern Web Stack: Running a Local Web Server Why Bundling?

So if everything is working, what do we need webpack for? Well consider if you were now planning to release this as a product. You want to be able to say Hello webpack to the entire world! You're hoping to get a minimum of 1 million unique visitors per day.

You take your project directory and you upload it to your web server. You need to make sure you also include the node_modules folder because that's where the Lodash library is. Every time our page loads, it loads the lodash.min.js file. Every one of our million users per day (disregarding cache and gzip options for the moment) will be downloading this file.

Lodash is a huge library that comes with tons of great functions for all kinds of different use cases. Even after being minified, our lodash.min.js file is still a sizable 73KB. That's 73KB of data for every user just to gain access to the join() function.

Wouldn't it be great if we could just extract that join() function and leave behind all the excess parts of the library we aren't using?

That's where webpack comes in.

Installing Webpack npm install webpack webpack-cli --save-dev Enter fullscreen mode Exit fullscreen mode

Let's take a look at what each one is doing:

webpack - This is the main engine of webpack, it understands everything related about how the code and files relate to one another, and how to bundle them into a single package.

webpack-cli - This is the actual program we are going to run to trigger the core engine. It allows us to run webpack on our command line and generate a bundle.

Our first goal will be to simply configure webpack to process our script.js file and output it without doing any transformations. We'll add those in soon after.

Create a new file in the root directory called webpack.config.js with the following code:

webpack.config.js

const path = require("path"); module.exports = { mode: "none", entry: "./src/script.js", output: { filename: "main.js", path: path.resolve(__dirname, "dist"), }, }; Enter fullscreen mode Exit fullscreen mode

Before we fun this, let's look at what we expect it will do:

mode - This determines what kind of extra processing is done to your output file.

none - No extra processing at all. We are using this for the tutorial because it makes the output file cleaner for a human to read and understand. development - Extra work done to add features that make debugging and tracing issues easier. Will be slower and result in larger file sizes. Designed only to be used during development. production - Removes all unnecessary code and only produces the smallest and leanest file possible. Designed for your release build.

entry - The starting point of our app, it's pointing to our script.js file with our Javascript code

output - This is the name and location of the file it fill generate after all the bundling is done. This is the file our index.html file will load. Includes both the name of the file and path. We are going to output everything into a directory called dist

Let's run webpack now and see if our assumptions are true. ON your terminal run:

npx webpack Enter fullscreen mode Exit fullscreen mode

We don't need any arguments with that command because it gets all the config information it needs automatically from your webpack.config.js file. At this point you should see a file generated called main.js in your dist folder that looks nearly identical to your script file.

The idea is that your entire project gets bundled into the dist directory and that is what you upload to your server as your release build. OUr issue right now however is that neither your index.html nor your node_modules folder existed in your dist folder. If you tried to release your project now there would be nothing to load.

We will start by configuring webpack to bundle your index.html in your output. We could technically just copy it in there ourselves, but of course webpack has its own way of handling that. This is where we introduce our first plugin.

Webpack Plugins

Plugins are code that give webpack additional information about how to perform certain tasks. The most common one you will use is called HtmlWebpackPlugin. Its purpose is exactly as we described above, to let you include an HTML file in your output bundle.

Before we can use it, we have to add it to our project. Run the following command:

npm install html-webpack-plugin --save-dev Enter fullscreen mode Exit fullscreen mode

Once that is installed we update our webpack config file:

webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin"); //


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有